/*
 * MENU.c
 *
 * Created: 24.09.2012 17:55:40
 *  Author: mariuvi
 */ 
#include "MENU.h"
#include "DISPLAY.h"
#include "JOY.h"
#include "definitions.h"
#include <avr/io.h>

typedef const struct MenuStucture
{
	const char* text;
	int numMenupoints;
	int up;
	int down;
	int enter;
	void (*fp) (void);
} MenuEntry;

unsigned char MENU_selected = 0;

const char menu_000[] = "Ping pong";
const char menu_001[] = "Options";
const char menu_002[] = "Etc";
const char menu_003[] = "Options";
const char menu_004[] = "Options2";
const char menu_005[] = "Options3";



const char menu_100[] = "Play";
const char menu_101[] = "Return";
const char menu_102[] = "LALALA";

MenuEntry MENU_menu[] =
{
	{menu_000, 6, 0, 1, 6, 0}, //0
	{menu_001, 6, 0, 2, 1, 0}, //1
	{menu_002, 6, 1, 3, 2, 0}, //2	 
	{menu_003, 6, 2, 4, 3, 0}, //3
	{menu_004, 6, 3, 5, 4, 0}, //4
	{menu_005, 6, 4, 5, 5, 0}, //5
		
	{menu_100, 3, 6, 7, 6, 0}, //6
	{menu_101, 3, 6, 8, 7, 0}, //7
	{menu_102, 3, 7, 8, 1, 0}  //8
};

void MENU_print_menu()
{
	int till = 0;
	int from;
	
	//Calculates till and from
	while(till<=MENU_selected)
	{
		till += MENU_menu[till].numMenupoints;
	}
	from = till - MENU_menu[MENU_selected].numMenupoints;
	till -= 1;
	
	//Marker formatting in menu
	//Top of menu
	if(MENU_selected == from)
	{
		DISPLAY_move_marker(UP);
		DISPLAY_move_menu(MENU_menu[from].text, MENU_menu[from+1].text, MENU_menu[from+2].text);
	}
	else if(MENU_selected == till)
	{
		DISPLAY_move_marker(DOWN);
		DISPLAY_move_menu(MENU_menu[till-2].text, MENU_menu[till -1].text, MENU_menu[till].text);
	}
	else 
	{
		DISPLAY_move_marker(NEUTRAL);
		DISPLAY_move_menu(MENU_menu[MENU_selected-1].text, MENU_menu[MENU_selected].text, MENU_menu[MENU_selected+1].text);
	}
	DISPLAY_print();
}

void MENU_browse()
{
	unsigned int browse;
	
	//Sets up a timer with a 1/64 clock
	BIT_SET(TCCR1B,CS10);
	BIT_SET(TCCR1B,CS11);	
	while(1)
	{
		if((TCNT1 > 38378) && (browse == FALSE))
		{
			browse = TRUE;
		}
		
		//We only browse once every 0.5s
		if(browse == TRUE)
		{						
			JOY_Pos position = JOY_read();	
			if(JOY_button_pressed())
			{
				MENU_selected = MENU_menu[MENU_selected].enter;
				TCNT1 = 0;
				browse = FALSE;
				MENU_print_menu();
			}
			else if(position.dir == UP)
			{
				MENU_selected = MENU_menu[MENU_selected].up;
				TCNT1 = 0;
				browse = FALSE;
				MENU_print_menu();
			}
			else if(position.dir == DOWN)
			{
				MENU_selected = MENU_menu[MENU_selected].down;
				TCNT1 = 0;
				browse = FALSE;
				MENU_print_menu();
			}
		}			
	}
}